<template>
  <div class="upload-file">
    <el-upload multiple :action="uploadFileUrl" :fileList="fileList" :before-upload="handleBeforeUpload" :limit="limitss" :on-change="handleChange" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="true" :headers="upload.headers" class="upload-file-uploader"  ref="uploadShpRef" :auto-upload="true" style="display: inline-block" :disabled="disabled" drag>
      <el-icon class="el-icon--upload">
        <upload-filled />
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <!-- 上传提示 -->
        <div class="el-upload__tip text-center">
          <template>
            支持上传多个文件。
          </template>
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limitss: {
    type: Number,
    default: 10,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1024,
  },
  // 是否是空间数据
  isSpatialData: {
    type: Number,
    default: 0,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileTypes: {
    type: Array,
    //default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  code: {
    type: String,
    default: '',
  },
  isHasFile: {
    type: Number,
    default: 0,
  }
});
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile", // 上传的图片服务器地址
});
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile"); // 上传的图片服务器地址
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const fileList = ref([]);

watch(() => props.modelValue, val => {
  // debugger
  if (val) {

    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.attachId = item.attachId || new Date().getTime() + temp++;
      item.name = item.attachName;
      item.url = item.attachPath;
      return item;
    });
    console.log(fileList.value, '回显数据');
  } else {
    fileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });

// 上传前校检格式和大小
function handleBeforeUpload (file) {
  console.log(props.limitss,'geshu');
  // 校检文件类型
  if (props.fileTypes.length) {
    let fileExtension = ""; 
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileTypes.some((type) => {
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileTypes.join("/")}格式文件!`);
      return false;
    }
  }

  // if (!props.fileTypes.length) {
  //   // 非第一次上传
  //   if (fileList.value.length) {
  //     var falg = fileList.value.some(item => {
  //       const name = item.name.slice(0, item.name.lastIndexOf("."));
  //       const fileName = file.name.slice(0, file.name.lastIndexOf("."));
  //       if (name != fileName) {
  //         const uploadName = fileList.value[0].name.slice(0, fileList.value[0].name.lastIndexOf("."));
  //         proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
  //         return true;
  //       }
  //     })
  //     if (falg) { return false; }
  //     var falg1 = fileList.value.some(item => {
  //       const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
  //       const typeFileName = file.name.slice(file.name.lastIndexOf(".") + 1)
  //       if ((typeName == 'shp' && typeFileName == typeName) || (typeName == 'dbf' && typeFileName == typeName) || (typeName == 'prj' && typeFileName == typeName) || (typeName == 'shx' && typeFileName == typeName) || (typeName == 'cpg' && typeFileName == typeName)) {
  //         proxy.$modal.msgError(`该类型文件只能上传一个!`);
  //         return true;
  //       }
  //     })
  //     if (falg1) { return false; }
  //   }
  // }

  // 校检文件大小
  if (props.fileSize) {
    const isLt = (file.size / 1024 / 1024 <= props.fileSize);
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  upload.isUploading = true;
  number.value++;
  return true;
}

function handleChange (file, fileList) {
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed () {
  console.log(props.limitss,'2222');
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limitss} 个!`);
}

// 上传失败
function handleUploadError (err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess (res, file) {
  if (res.code == 200) {
    uploadList.value.push({ attachId: res.data[0].attachId, name: res.data[0].attachName, url: res.data[0].attachPath });
    console.log(JSON.parse(JSON.stringify(fileList.value)))
    if (uploadList.value.length === number.value) {
      fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
      uploadList.value = [];
      number.value = 0;
      //emit("update:modelValue", listToString(fileList.value));
      proxy.$modal.closeLoading();
      proxy.$modal.msgSuccess("上传文件成功");
      emit('uploadFile', res.data[0].attachId);
    }
  }
}

// 删除文件
function handleDelete (index, file) {
  fileList.value = [];
  emit('delFile', fileList.value);
}

// 下载文件
function handleDownload (file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

// 获取文件名称
function getFileName (name) {
  return name
}

defineExpose({
  fileList
});
</script>